package com.ethink.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.db.PageUtils;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.id.generator.IdGenerator;
import com.ethink.order.api.constant.OrderConstant;
import com.ethink.order.api.enums.TobSaleOrderOrderStatusEnum;
import com.ethink.order.api.info.TobSaleDetailOrderInfo;
import com.ethink.order.api.info.TobSaleOrderInfo;
import com.ethink.order.api.model.TobSaleAndSettleModel;
import com.ethink.order.api.model.TobSaleOrderAndReturnModel;
import com.ethink.order.api.model.TobSaleOrderGoodsModeModel;
import com.ethink.order.api.model.TobSaleOrderModel;
import com.ethink.order.api.request.*;
import com.ethink.order.api.response.TobSaleOrderAddResponse;
import com.ethink.order.common.entity.TobSaleDetailOrder;
import com.ethink.order.common.entity.TobSaleOrder;
import com.ethink.order.common.mapper.TobSaleDetailOrderMapper;
import com.ethink.order.common.mapper.TobSaleOrderMapper;
import com.ethink.order.manager.SaleChannelRequestManager;
import com.ethink.order.service.TobSaleDetailOrderService;
import com.ethink.order.service.TobSaleOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TOB销售单 Service接口实现
 *
 * @author default
 * @date 2022-11-16
 */
@Slf4j
@Service
public class TobSaleOrderServiceImpl implements TobSaleOrderService {

    @Autowired
    private TobSaleOrderMapper tobSaleOrderMapper;

    @Autowired
    private TobSaleDetailOrderService tobSaleDetailOrderService;

    @Autowired
    private TobSaleDetailOrderMapper tobSaleDetailOrderMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Override
    public TobSaleOrderAddResponse addTobSaleOrder(TobSaleOrderAddRequest request) {
        //唯品校验po单号
        if (OrderConstant.Z102.equals(request.getSaleSubChannel())) {
            Integer count = tobSaleOrderMapper.selectCount(new LambdaQueryWrapper<TobSaleOrder>()
                    .eq(TobSaleOrder::getPoOrderNo, request.getPoOrderNo())
                    .eq(TobSaleOrder::getIsDeleted,false));
            if (count > 0) {
                throw new BusinessException(CommonRespCode.PARAM_ERR, "po单号重复");
            }
        }
        String orderNo = idGenerator.tob();
        request.setOrderNo(orderNo);
        TobSaleOrder tobSaleOrder = new TobSaleOrder();
        BeanUtils.copyProperties(request, tobSaleOrder, "item");
        tobSaleOrderMapper.insert(tobSaleOrder);
        //保存商品信息
        tobSaleDetailOrderService.batchInsert(request.getItem(), orderNo);
        TobSaleOrderAddResponse response = new TobSaleOrderAddResponse();
        response.setTobSaleOrderInfo(queryTobSaleOrderById(tobSaleOrder.getId()));
        response.setTobSaleDetailOrderInfoList(tobSaleDetailOrderMapper.selectTobSaleDetailByOrderNo(orderNo));
        return response;
    }

    @Override
    public Page<TobSaleOrderModel> pageQueryTobSaleOrder(TobSaleOrderPageQueryRequest request) {
        return tobSaleOrderMapper.pageQuery(PageUtils.buildPage(request), request);
    }

    @Override
    public void deleteTobSaleOrder(Long id) {
        TobSaleOrder tobSaleOrder = tobSaleOrderMapper.selectById(id);
        tobSaleOrderMapper.delById(id);
        tobSaleDetailOrderMapper.update(null, new LambdaUpdateWrapper<TobSaleDetailOrder>()
                .eq(TobSaleDetailOrder::getOrderNo, tobSaleOrder.getOrderNo())
                .set(TobSaleDetailOrder::getIsDeleted, true));
    }

    @Override
    public TobSaleOrderInfo queryTobSaleOrderById(Long id) {
        TobSaleOrder tobSaleOrder = tobSaleOrderMapper.selectById(id);
        if (ObjectUtil.isEmpty(tobSaleOrder)) {
            return null;
        }
        return BeanUtil.copyProperties(tobSaleOrder, TobSaleOrderInfo.class);
    }

    @Override
    public Page<TobSaleAndSettleModel> tobSaleAndSettlePageQuery(TobSaleAndSettlePageQueryRequest request) {
        SaleChannelRequestManager.fill(request, 0, 1, 2);
        return tobSaleOrderMapper.tobSaleAndSettlePageQuery(PageUtils.buildPage(request), request);
    }

    @Override
    public void updateTobSaleOrderStatus(TobSaleOrderSetStatusRequest request) {
        tobSaleOrderMapper.update(null, new LambdaUpdateWrapper<TobSaleOrder>()
                .eq(TobSaleOrder::getId, request.getId())
                .set(TobSaleOrder::getOrderStatus, request.getOrderStatus())
        );
    }

    @Override
    public Boolean checkSettleImport(TobSettleImportCheckRequest checkRequest) {
        List<TobSaleOrder> tobSaleOrders = tobSaleOrderMapper.selectList(new LambdaQueryWrapper<TobSaleOrder>()
                .in(TobSaleOrder::getPoOrderNo, checkRequest.getPoSet())
                .eq(TobSaleOrder::getSaleChannel, checkRequest.getSaleChannel())
                .eq(TobSaleOrder::getSaleSubChannel, checkRequest.getSaleSubChannel()));
        return tobSaleOrders.size() == checkRequest.getPoSet().size();
    }

    @Override
    public Integer TobSaleOrderPoInsert(TobSaleOrderPoInsertRequest request) {
        TobSaleOrder tobSaleOrder = tobSaleOrderMapper.selectById(request.getId());
        if (TobSaleOrderOrderStatusEnum.S5.eq(tobSaleOrder.getOrderStatus())) {
            throw new BusinessException(CommonRespCode.PARAM_ERR, "订单已完成,无法操作");
        }
        return tobSaleOrderMapper.update(null, new LambdaUpdateWrapper<TobSaleOrder>()
                .eq(TobSaleOrder::getId, request.getId())
                .set(TobSaleOrder::getPoOrderNo, request.getPoOrderNo()));
    }

    @Override
    public TobSaleOrderInfo getTobSaleOrderInfoByOrderNo(String orderNo) {
        TobSaleOrder tobSaleOrder = tobSaleOrderMapper.selectOne(
                new LambdaQueryWrapper<TobSaleOrder>().eq(TobSaleOrder::getOrderNo, orderNo));
        if (ObjectUtil.isEmpty(tobSaleOrder)) {
            return null;
        }
        return BeanUtil.copyProperties(tobSaleOrder, TobSaleOrderInfo.class);
    }

    @Override
    public Boolean settleStatus(List<String> orderNo) {
        if (CollUtil.isEmpty(orderNo)) {
            return true;
        }
        return tobSaleOrderMapper.update(null, new LambdaUpdateWrapper<TobSaleOrder>()
                .in(TobSaleOrder::getOrderNo, orderNo)
                .set(TobSaleOrder::getOrderStatus, TobSaleOrderOrderStatusEnum.S4.getIntValue())) > 0;
    }

    @Override
    public List<String> queryDetailOrderNoByOrderNo(List<String> orderNo) {
        return tobSaleDetailOrderMapper.queryDetailOrderNoByOrderNo(orderNo);
    }

    @Override
    public List<TobSaleOrderAndReturnModel> queryToBeSettleDetail(List<String> mateSkuList, String saleSubChannel, List<String> poList) {
        return tobSaleDetailOrderMapper.queryToBeSettleDetail(mateSkuList, saleSubChannel, poList);
    }

    /**
     * 分页查询
     *
     * @param request
     * @return
     */
    @Override
    public Page<TobSaleOrderGoodsModeModel> pageQueryTobSaleOrderPageMode(TobSaleOrderPageGoodsModeQueryRequest request) {
        return tobSaleOrderMapper.pageQueryTobSaleOrderPageMode(PageUtils.buildPage(request), request);
    }

    @Override
    public void batchSettleOrder(List<String> orderNos) {
        if (CollUtil.isEmpty(orderNos)){
            return;
        }
        for (String orderNo : orderNos) {
            List<TobSaleDetailOrderInfo> tobSaleDetailOrderInfos = tobSaleDetailOrderMapper
                    .selectTobSaleDetailByOrderNo(orderNo);

            //如果未结算订单数量 = 0 则预售单订单状态变成已完成
            int size = tobSaleDetailOrderInfos.stream().filter(a -> a.getIsSettle() == 0).collect(Collectors.toList()).size();
            if (size == 0) {
                tobSaleOrderMapper.update(null,new LambdaUpdateWrapper<TobSaleOrder>()
                        .eq(TobSaleOrder::getOrderNo,orderNo)
                        .set(TobSaleOrder::getOrderStatus, TobSaleOrderOrderStatusEnum.S5.getIntValue()));
            }
        }
    }

    @Override
    public List<TobSaleOrderAndReturnModel> queryToBeSettleDetailByPo(List<String> mateSkuList, String saleSubChannel, List<String> poAndSkuList) {
        return tobSaleDetailOrderMapper.queryToBeSettleDetailByPo(mateSkuList, saleSubChannel, poAndSkuList);
    }
}
